package mamikeji.liaowa.ui.fragment.favorite;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.MyFavoriteTopic;
import mamikeji.liaowa.bean.MyForumBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.circle.FriendMSGActivity;
import mamikeji.liaowa.ui.activity.forum.ForumMSGActivity;
import mamikeji.liaowa.ui.adapter.TopicRecyclerViewAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.main_view.PullLoadMoreRecyclerView;

/**
 * Created by 叶寅 on 2017/9/4.
 */

public class TopicFragment extends Fragment {
    private static final String TAG = "Main_ForumFragment";
    private static final int TAG_CIRCLE = 1001;
    private static final int TAG_FORUM = 1002;
    private static final int TAG_PUBLISH_FORUM = 1004;
    View mView;
    @BindView(R.id.favorite_recyclerView)
    PullLoadMoreRecyclerView favoriteRecyclerView;
    //    @BindView(R.id.ptrlDownRefreshFrameLayout_my_collection_forum_list)
//    PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayoutMyCollectionForumList;
    @BindView(R.id.multiStateView_my_collection_forum)
    MultiStateView multiStateViewMyCollectionForum;
    private RecyclerView mRecyclerView;

    //每页显示条数
    private String PAGE_ITEM = "2";
    private String USER_CODE_FAVORITE = "6a0f0039-3f31-4274-a84d-ac5b1d9d1c4c";
    //页数
    private int PAGE = 1;
    //总共有多少条目
    private int TOTALITEM;
    //总共有多少页
    private int PAGESIZE;
    private static final String TAG_DATA = "TopicFragmentgetDataCollction";

    //话题数据集
    private List<MyForumBean.DataEntity> dataEntityList = new ArrayList<>();
    //话题每页的活动数据集合
    ArrayList<MyForumBean.DataEntity> mList;

    private int list_item_num = -1;


    private TopicRecyclerViewAdapter topicRecyclerViewAdapter;
    private List<MyFavoriteTopic.DataMyFavoriteTopicList> data;

    private int totalItem;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_favorite_topic, container, false);
        ButterKnife.bind(this, mView);

        init();
        return mView;
    }

    public void init() {
        multiStateViewMyCollectionForum.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getCollection_ForumData(1, 10);
                    }
                });

//        ptrlDownRefreshFrameLayoutMyCollectionForumList.setPtrHandler(new PtrDefaultHandler() {
//            @Override
//            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//                return PtrDefaultHandler.checkContentCanBePulledDown(frame, favoriteRecyclerView.getRecyclerView(), header);
//            }
//
//            @Override
//            public void onRefreshBegin(PtrFrameLayout frame) {
//
//            }
//        });

        //获取首页朋友圈
        getCollection_ForumData(1, 10);

        //获取mRecyclerView对象
        mRecyclerView = favoriteRecyclerView.getRecyclerView();
        //代码设置scrollbar无效？未解决！
        mRecyclerView.setVerticalScrollBarEnabled(true);
//        设置下拉刷新是否可见
        favoriteRecyclerView.setRefreshing(false);
//        设置是否可以下拉刷新
        favoriteRecyclerView.setPullRefreshEnable(false);
        //设置是否可以上拉刷新
        //favoriteRecyclerView.setPushRefreshEnable(false);
        //显示下拉刷新
        favoriteRecyclerView.setRefreshing(true);
        //设置上拉刷新文字
        favoriteRecyclerView.setFooterViewText("正在加载···");
//        设置上拉刷新文字颜色
        favoriteRecyclerView.setFooterViewTextColor(R.color.color_app);
        //设置加载更多背景色
        //favoriteRecyclerView.setFooterViewBackgroundColor(R.color.colorBackground);
        favoriteRecyclerView.setLinearLayout();

        topicRecyclerViewAdapter = new TopicRecyclerViewAdapter(getActivity(), dataEntityList);

        favoriteRecyclerView.setAdapter(topicRecyclerViewAdapter);

        favoriteRecyclerView.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {

                if (PAGE > totalItem) {
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            ForToast.showToast(R.string.error_down_end);
                            //刷新数据
                            //设置是否可以上拉刷新
                            favoriteRecyclerView.setPushRefreshEnable(false);
                            topicRecyclerViewAdapter.notifyDataSetChanged();
                            favoriteRecyclerView.setPullLoadMoreCompleted();
                        }
                    }, 1000);
                } else {
                    PAGE++;
                    getCollection_ForumData(PAGE, 10);
                }
            }
        });

        topicRecyclerViewAdapter.setItemClickListener(new TopicRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int num = dataEntityList.get(position).getBrowse_total();
                dataEntityList.get(position).setBrowse_total(num++);
                topicRecyclerViewAdapter.notifyDataSetChanged();
                Intent intent = new Intent(getActivity(), ForumMSGActivity.class);
                intent.putExtra("MyForumBean", dataEntityList.get(position));
                startActivity(intent);
            }

            @Override
            public void onZanClick(int position) {
                getFabulousForum(position);
            }

            @Override
            public void onGuanZhuClick(int position) {
            }

            @Override
            public void onMSGClick(int position) {
                Intent mIntent = new Intent(getActivity(), FriendMSGActivity.class);
                mIntent.putExtra(HttpKey.Friend_MSG_friendcode, dataEntityList.get(position).getUsercode());
                startActivityForResult(mIntent, TAG_CIRCLE);
            }

            @Override
            public void onCanelCollection(int position) {
                initCollectionDate(position);
            }
        });
    }

    /**
     * 获取收藏话题数据
     *
     * @param indexpage
     * @param pagesize
     * @return
     */
    public void getCollection_ForumData(int indexpage, int pagesize) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.My_favorite_current, indexpage + "");
        formMap.put(HttpKey.My_favorite_pagesize, pagesize + "");
        formMap.put(HttpKey.My_favorite_topic_id, "1");
        formMap.put(HttpKey.My_favorite_usercode, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.My_Favorite, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
//                ptrlDownRefreshFrameLayoutMyCollectionForumList.refreshComplete();
                multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG + "getMain_FriendCircleData", response);
//                ptrlDownRefreshFrameLayoutMyCollectionForumList.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        MyForumBean bean = new Gson().fromJson(response, MyForumBean.class);

                        if (PAGE == 1) {
                            totalItem = bean.getTotal();

                            if (totalItem % 10 > 0) {
                                totalItem = totalItem / 10 + 1;
                            } else {
                                totalItem = totalItem / 10;
                            }
                        }

                        mList = (ArrayList<MyForumBean.DataEntity>) bean.getData();

                        if (mList != null && mList.size() > 0) {
                            if (PAGE == 1) {
                                dataEntityList.clear();
                                dataEntityList.addAll(mList);
                                ForLog.i("dataList_size", dataEntityList.size() + "");

                                //刷新数据
                                //topicRecyclerViewAdapter.refreshDate(dataEntityList);

                                topicRecyclerViewAdapter.notifyDataSetChanged();

                                favoriteRecyclerView.setPullLoadMoreCompleted();


                            } else {
                                //加载更多
                                dataEntityList.addAll(mList);
                                topicRecyclerViewAdapter.notifyDataSetChanged();
                                favoriteRecyclerView.setPullLoadMoreCompleted();
                            }

                            multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (PAGE == 1) {
                                multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            } else {
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        ForToast.showToast(R.string.error_down_end);
                                        //刷新数据
                                        topicRecyclerViewAdapter.notifyDataSetChanged();
                                        favoriteRecyclerView.setPullLoadMoreCompleted();
                                    }
                                }, 1000);
                                multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            }
                        }
                    } else {
                        multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 点赞
     */
    private void getFabulousForum(final int position) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.Forum_Praise_usercode, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.Forum_Praise_topic_id, dataEntityList.get(position).getTopic_id() + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SendTopicPraise, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        int num = dataEntityList.get(position).getPraise_total();
                        if (dataEntityList.get(position).getIs_praise() == 1) {
                            dataEntityList.get(position).setIs_praise(0);
                            dataEntityList.get(position).setPraise_total(--num);
                        } else {
                            dataEntityList.get(position).setIs_praise(1);
                            dataEntityList.get(position).setPraise_total(++num);
                        }
                        topicRecyclerViewAdapter.notifyDataSetChanged();
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /**
     * 收藏文章
     */
    private void initCollectionDate(final int position) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put("usercode", ForPreference.getString(ForContents.USER_CODE));
        formMap.put("topic_id", dataEntityList.get(position).getTopic_id() + "");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.SendTopicCollection, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
            }

            @Override
            public void onResponse(String response) {
                ForLog.e(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        dataEntityList.remove(position);
                        if (dataEntityList.size() == 0) {
                            multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        } else {
                            multiStateViewMyCollectionForum.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        }
                        topicRecyclerViewAdapter.notifyDataSetChanged();

                        int num = ForPreference.getInt(ForContents.USER_COLLECTION);
                        ForPreference.putInt(ForContents.USER_COLLECTION, --num);
                        ForToast.showToast(R.string.collection_delete);
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == TAG_FORUM) {

            }
        }
    }

//    @Override
//    protected void initData() {
//        //网络参数
//        Map<String, String> formMap = getStringStringMap("1", PAGE_ITEM, USER_CODE_FAVORITE);
//        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.My_Favorite, formMap, new StringCallback() {
//            @Override
//            public void onError(Request request, Exception e) {
//                ForLog.i(TAG, e.getMessage());
//                ForToast.showToast(R.string.intent_error);
//            }
//
//            @Override
//            public void onResponse(String response) {
//                ForLog.i(TAG, response);
//                try {
//                    JSONObject jsonObject = new JSONObject(response);
//                    String status = jsonObject.getString(HttpKey.STATUS);
//
//                    if ("200".equals(status)) {
//                        MyFavoriteTopic myFavoriteTopic = new Gson().fromJson(response, MyFavoriteTopic.class);
//
//                        getPageSize(myFavoriteTopic.getTotal());
//
//                        if (myFavoriteTopic.getData() != null) {
//                            ForLog.i(TAG_DATA, myFavoriteTopic.getData());
//
//                            data = myFavoriteTopic.getData();
//
//                            topicRecyclerViewAdapter = new TopicRecyclerViewAdapter(mFavoriteRecyclerView.getContext(), data);
//
//                            mFavoriteRecyclerView.setAdapter(topicRecyclerViewAdapter);
//
//                            LinearLayoutManager layoutManager = new LinearLayoutManager(mFavoriteRecyclerView.getContext());
//                            mFavoriteRecyclerView.setLayoutManager(layoutManager);
//                        }
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//    }
//
//
//    @Override
//    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
//
//        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.My_Favorite, getStringStringMap("1", PAGE_ITEM, USER_CODE_FAVORITE), new StringCallback() {
//            @Override
//            public void onError(Request request, Exception e) {
//                ForLog.i(TAG, e.getMessage());
//                ForToast.showToast(R.string.intent_error);
//            }
//
//            @Override
//            public void onResponse(String response) {
//                mRefreshLayout.endRefreshing();
//                try {
//                    JSONObject jsonObject = new JSONObject(response);
//                    String status = jsonObject.getString(HttpKey.STATUS);
//                    if ("200".equals(status)) {
//                        MyFavoriteTopic myFavoriteTopic = new Gson().fromJson(response, MyFavoriteTopic.class);
//
//                        getPageSize(myFavoriteTopic.getTotal());
//
//                        if (myFavoriteTopic.getData() != null) {
//
//                            ForLog.i(TAG_DATA, myFavoriteTopic.getData());
//
//                            data.clear();
//
//                            data.addAll(myFavoriteTopic.getData());
//
//                            topicRecyclerViewAdapter.notifyDataSetChanged();
//                        }
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//    }
//
//    @Override
//    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
//        if (PAGE <= PAGESIZE) {
//            PAGE += 1;
//            ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.My_Favorite, getStringStringMap(PAGE + "", PAGE_ITEM, USER_CODE_FAVORITE), new StringCallback() {
//                @Override
//                public void onError(Request request, Exception e) {
//                    ForLog.i(TAG, e.getMessage());
//                    ForToast.showToast(R.string.intent_error);
//                }
//
//                @Override
//                public void onResponse(String response) {
//                    mRefreshLayout.endLoadingMore();
//                    try {
//                        JSONObject jsonObject = new JSONObject(response);
//                        String status = jsonObject.getString(HttpKey.STATUS);
//                        if ("200".equals(status)) {
//                            MyFavoriteTopic myFavoriteTopic = new Gson().fromJson(response, MyFavoriteTopic.class);
//
//                            if (myFavoriteTopic.getData() != null) {
//                                ForLog.i(TAG_DATA, myFavoriteTopic.getData());
//
//                                data.addAll(myFavoriteTopic.getData());
//
//                                topicRecyclerViewAdapter.notifyDataSetChanged();
//                            }
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//
//                }
//            });
//            return true;
//        } else {
//            ForToast.showToast("没有更多数据了...");
//            return false;
//        }
//
//
//    }
//
//    public void getPageSize(int total) {
//
//        PAGESIZE = total / new Integer(PAGE_ITEM);
//
//        if (total % new Integer(PAGE_ITEM) > 0) {
//            PAGESIZE += 1;
//        }
//    }
//
//    protected Map<String, String> getStringStringMap(String page, String pageItem, String userCode) {
//        //参数集合
//        Map<String, String> formMap = new HashMap<String, String>();
//        //第几页数据
//        formMap.put(HttpKey.My_favorite_current, page);
//        //1页数据有几条
//        formMap.put(HttpKey.My_favorite_pagesize, pageItem);
//        //用户标示
//        formMap.put(HttpKey.My_favorite_usercode, userCode);
//
//        formMap.put(HttpKey.My_favorite_topic_id, "0");
//
//        return formMap;
//    }
}
